package main

import (
	"learn/learn/socket/internal/protocol"
	"net"
)

func main() {
	var (
		err    error
		conn   net.Conn
		listen net.Listener
		data   = make(chan []byte, 16)
	)
	defer func() {
		if err != nil {
			println(err.Error())
		}
	}()
	listen, err = net.Listen("tcp", "0.0.0.0:9000")
	if err != nil {
		return
	}
	go func() {
		for {
			select {
			case val := <-data:
				println(string(val))
			}
		}
	}()
	for {
		conn, err = listen.Accept()
		if err != nil {
			break
		}
		go handleConnection(conn, data)
	}
}
func handleConnection(conn net.Conn, date chan<- []byte) {
	defer conn.Close()
	var (
		tmp []byte
		res = make([]byte, 0, 1024)
	)
	for {
		n, err := conn.Read(res)
		if n > 0 {
			dataToRead := res[:n]
			if tmp != nil {
				dataToRead = append(tmp, dataToRead...)
				tmp = nil // 重置剩余数据
			}
			tmp = protocol.DePack(dataToRead, date)
		}
		if err != nil {
			break
		}
	}
}
